/**
 * Copyright &copy; 2020 <a href="https://github.com/somowhere/exam-system">exam-system</a> All rights reserved.
 */
package com.shanhesoft.java.modules.exam.web;


import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.ApiOperation;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanhesoft.java.common.core.annotation.AnonymousAccess;
import com.shanhesoft.java.common.core.constant.CommonConstants;
import com.shanhesoft.java.common.core.util.DateUtil;
import com.shanhesoft.java.common.core.util.Result;
import com.shanhesoft.java.common.core.util.StringUtil;
import com.shanhesoft.java.common.core.vo.PageModel;
import com.shanhesoft.java.common.data.util.QueryWrapperUtil;
import com.shanhesoft.java.common.web.resource.BaseResource;
import com.shanhesoft.java.modules.exam.domain.dto.CourseDto;
import com.shanhesoft.java.modules.exam.domain.dto.CourseQueryCriteria;
import com.shanhesoft.java.modules.exam.service.CourseService;
import com.shanhesoft.java.modules.tool.service.FileService;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import lombok.AllArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Set;

/**
 * 课程管理Controller 课程管理
 * @author admin
 * @version 2020-09-23 19:34:44
 */
@RestController
@RequestMapping(value = "${application.admin-path}/exam/course")
@Slf4j
@AllArgsConstructor
public class CourseResource extends BaseResource {

	private final CourseService service;

	private final FileService fileService;

	/**
	 * @param id
	 * @return
	 */
	@GetMapping(CommonConstants.URL_ID_REGEX)
	@PreAuthorize("@pms.hasPermission('exam_course_view')")
	public Result get(@PathVariable String id) {
		log.debug("REST request to get Entity : {}", id);
		return  Result.buildOkData(service.findCourseVoById(id));
	}
	/**
	 * GET / : get all course.
	 *
	 * @param pm the pagination information
	 * @return the Result with status 200 (OK) and with body all course
	 */

	//@PreAuthorize("@pms.hasPermission('exam_course_view')")
	@GetMapping
	@ApiOperation(value = "课程管理查看")
	public Result getPage(PageModel pm, CourseQueryCriteria courseQueryCriteria) {
//		QueryWrapper wrapper = QueryWrapperUtil.getWrapper(pm, courseQueryCriteria);
		return Result.buildOkData(service.findPage(pm, courseQueryCriteria));
	}

	/**
	 * 获取首页热门数据
	 *
	 * @return
	 * @author
	 * @date
	 */
	@AnonymousAccess
	@GetMapping("/getHomeCoursePage")
	@ApiOperation(value = "获取首页热门数据", notes = "获取首页热门数据")
	public Result getHomeCoursePage() {
		PageModel pm = new PageModel();
		pm.setCurrent(1);
		pm.setSize(3);
		CourseQueryCriteria courseQueryCriteria = new CourseQueryCriteria();
		return Result.buildOkData(service.findPage(pm, courseQueryCriteria));
	}


	/**
	 * GET / : get all terms.
	 *
	 * @return the Result with status 200 (OK) and with body all terms
	 */

	@GetMapping("/getAll")
	@ApiOperation(value = "课程管理查看")
	public Result getAllNoPage(CourseQueryCriteria courseQueryCriteria) {
		QueryWrapper wrapper = QueryWrapperUtil.getWrapper(courseQueryCriteria);
		return Result.buildOkData(service.list(wrapper));
	}

	/**
	 * POST / : Save a courseDto.
	 *
	 * @param courseDto the HTTP course
	 */
	@PreAuthorize("@pms.hasPermission('exam_course_edit')")
	@ApiOperation(value = "课程管理编辑")
	@PostMapping
	public Result save(@Valid @RequestBody CourseDto courseDto) {
		log.debug("REST request to save CourseDto : {}", courseDto);
		service.saveOrUpdate(courseDto);
		return Result.buildOk("保存课程管理成功");

	}

	/**
	 * DELETE //:ids : delete the "ids" Course.
	 *
	 * @param ids the id of the course to delete
	 * @return the Result with status 200 (OK)
	 */
	@PreAuthorize("@pms.hasPermission('exam_course_del')")
	@ApiOperation(value = "课程管理删除")
	@DeleteMapping
	public Result delete(@RequestBody Set<String> ids) {
		log.debug("REST request to delete Course: {}", ids);
		service.removeByIds(ids);
		return Result.buildOk("删除课程管理成功");
	}

	@ApiOperation(value = "文件上传")
	@PostMapping(value = "/localUpload")
	public Result localUpload(MultipartFile file, HttpServletRequest request) {
		if (file.isEmpty()) {
			return Result.buildFail("文件内容为空");
		}

		String fileTempPath = "";
		String fileName = file.getOriginalFilename();
		String rawFileName = StringUtil.subBefore(fileName, ".", true);
		String fileType = StringUtil.subAfter(fileName, ".", true);
		String localFilePath = StringUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
		try {
			file.transferTo(new File(localFilePath));
		} catch (IOException e) {
			log.error("【文件上传至本地】失败，绝对路径：{}", localFilePath);
			return Result.buildFail("文件上传失败");
		}

		log.info("【文件上传至本地】绝对路径：{}", localFilePath);
		return Result.buildOk("文件上传成功");
	}
}
